import qs from 'qs'
import jsCookie, { CookieAttributes } from 'js-cookie'
/**
 * 授权基本类
 */
export class BaseAuth {
    /**
   * 解析 locaction.search 和 Hash中的search
   * **微信授权后的回调地址的code 和 state, 在pc端会添加到 search中, 在微信端会添加到 hash中**
   * @param search 
   * @returns { Object }
   */
  static parseQuery (search: string = window.location.search): {
    code?: string,
    appid?: string,
    state?: string
  } {
    const hash: string = window.location.hash
    if (search || (hash && hash.indexOf('?') > -1)) {
      search = search || '?' + hash.split('?')[1]
      return qs.parse(search, {
        ignoreQueryPrefix: true
      })
    }
    return {}
  }

  /**
   * 获取cookie
   * @param key 键名
   * @returns cookie值
   */
  static getCookie (key: string): string | undefined {
    return jsCookie.get(key)
  }
  /**
   * 
   * @param key {string} cookie 键名
   * @param value { any } cookie 键值
   * @param expires { number } 过期时间 
   */
  static setCookie (key: string, value: any, expires: number | Date | undefined) {
    const formatetExpires: CookieAttributes | undefined = expires ? {
      expires: expires
    } : undefined
    jsCookie.set(key, value, formatetExpires)
  }

  /**
   * 删除所有cookie
   */
   static removeAllCookie () {
    const all = jsCookie.get() // 获取所有的cookie
    for (const key in all) {
      jsCookie.remove(key) // 删除cookie
    }
  }

  /**
   * 随机字符串
   * @param len {number} - 随机字符串的长度
   * @returns {string}
   */
   static randomStr (len: number = 16) : string {
    const chars = 'ABCDEFGHJKMNPQRSTWXYZabcdefhijkmnprstwxyz2345678'
    const maxPos = chars.length
    let rand = ''
    for (let i = 0; i < len; i++) {
      rand += chars.charAt(Math.floor(Math.random() * maxPos))
    }
    return rand
  }

  /**
   * 格式化 过期时间
   * @param hours {number} - cookie 过期时间
   * @returns { Date } 返回时间格式
   */
   static createCookieExpires(hours: number = 0): Date {
    return new Date(new Date().getTime() + hours * 60 * 60 * 1000)
  }
}